<?php

class Topic extends CActiveRecord
{
	/**
	 * The followings are the available columns in table 'topic':
	 * @var integer $id
	 * @var string $label
	 * @var string $description
	 * @var integer $parent_id
	 * @var string $step_mnemonic
	 * @var integer $index
	 * @var integer $weeks_number
	 * @var integer $weeks_before
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'topic';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			array('label','length','max'=>200),
			array('label, orderIndex, active', 'required'),
			array('orderIndex, active, weeks_number', 'numerical', 'integerOnly'=>true),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'step' => array(self::BELONGS_TO, 'Step', 'step_id'),
			'parent' => array(self::BELONGS_TO, 'Topic', 'parent_id'),
			'topics' => array(self::HAS_MANY, 'Topic', 'parent_id', 'condition' => 'active = 1', 'order' => 'orderIndex'),
			'allTopics' => array(self::HAS_MANY, 'Topic', 'parent_id', 'order' => 'orderIndex'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => Yii::t('database', 'Id'),
			'label' => Yii::t('database', 'Label'),
			'description' => Yii::t('database', 'Description'),
			'parent_id' => Yii::t('database', 'Parent'),
			'step_id' => Yii::t('database', 'Step'),
			'orderIndex' => Yii::t('database', 'Index'),
			'active' => Yii::t('database', 'Active'),
			'weeks_number' => Yii::t('database', 'Weeks number'),
			'weeks_before' => Yii::t('database', 'Weeks before'),
		);
	}
	
	public function getKey() {
		return 'topic_' . $this->id;
	}
	
	public function getParent_key() {
		if ($this->step_id != null)
			return 'step_' .$this->step_id;
		else if ($this->parent_id != null) 
			return 'topic_' .$this->parent_id;
		else
			return '';
	}
	
	public function primaryKey()
	{
	    return 'id';
	}
	
}